<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Admin extends CI_Controller
{
    public function index()
    {
        $this->load->helper('url');
        Permission::check();
        $this->securitycenter->commonLogin();
        if ($_SESSION['user_type'] == 3) {//管理员
            header("location:" . site_url('/Administrator/task'));
            exit;
        } elseif ($_SESSION['user_type'] == 2) {
            header("location:" . site_url('/taskworker/task'));
            exit;
        } elseif ($_SESSION['user_type'] == 1) {
            header("location:" . site_url('/admin/task'));
            exit;
        } elseif ($_SESSION['user_type'] == 4) {
            header("location:" . site_url('/staff/task'));
            exit;
        }
    }

    public function task()
    {
        Permission::yy();
        $this->load->helper('url');
        $user_id = $_SESSION['user_id'];
        $isTheFristReceiveTask = 0;
        if ($this->lyw_common_model->isTheFristReceiveTask($user_id)) {
            $isTheFristReceiveTask = 1;
        } else {
            $isTheFristReceiveTask = 0;
        }
        $gonggao = '公告:' . file_get_contents(BASEPATH . '../assets/gonggao.txt');
        $data = array(
            'user_id' => $user_id,
            'user_type' => $_SESSION['user_type'],
            'header_json' => $this->lyw_common_model->buildHeaderJson(),
            'gonggao' => $gonggao,
            'isTheFristReceiveTask' => $isTheFristReceiveTask
        );
        $this->load->view('admin_task', $data);
    }

    public function getTaskJson()
    {
        //taskworker 也有用到
//        Permission::yy(1);
        $page = isset($_POST['page']) ? $_POST['page'] : 1;
        $rows = isset($_POST['rows']) ? $_POST['rows'] : 10;
        $this->load->model('Lyw_article_manager_model');
        //越期检查
        $this->lyw_common_model->translationOverDueCheck();
        $manager_list = $this->lyw_common_model->buildTaskJson($page, $rows);
        $count = $this->Lyw_article_manager_model->countIsNoDel();
        exit(json_encode(array('list' => $manager_list, 'count' => $count)));
    }

    public function login()
    {
        sessionOpen();
        $this->securitycenter->cookieLogin();
        //已登录状态
        if (isset($_SESSION['user_id']) && !empty($_SESSION['user_id']) && isset($_SESSION['user_type']) && !empty($_SESSION['user_type'])) {
            if ($_SESSION['user_type'] == 1) {
                header('location:' . site_url('/admin/task'));
            } elseif ($_SESSION['user_type'] == 2) {
                header('location:' . site_url('/taskworker/task'));
            } elseif ($_SESSION['user_type'] == 3) {
                header('location:' . site_url('/administrator/user'));
            } elseif ($_SESSION['user_type'] == 4) {
                header('location:' . site_url('/staff/task'));
            }
        }
        $token = md5(uniqid(rand(), TRUE));
        $_SESSION['token'] = $token;
        $_SESSION['token_time'] = time();
        $data = array(
            'token' => $token
        );
        $this->load->view('login', $data);
    }

    public function loginAttestation()
    {
        session_start();
        $p_token = isset($_POST['token']) ? $_POST['token'] : '';
        $username = isset($_POST['username']) ? $_POST['username'] : '';
        $password = isset($_POST['password']) ? $_POST['password'] : '';
        if (empty($username) || empty($password) || empty($p_token)) {
            exit(0);
        }
        if (isset($_SESSION['token']) && $p_token == $_SESSION['token']) {
            $token_age = time() - $_SESSION['token_time'];
            if ($token_age <= 300) {
                $this->load->model('lyw_user_model');
                $result = $this->lyw_user_model->attestation($username, $password);
                if ($result['code'] == 1) {
                    $_SESSION['user_id'] = $result['user_id'];
                    $_SESSION['username'] = $result['username'];
                    $_SESSION['user_type'] = $result['user_type'];
                    $_SESSION['header_image'] = $result['header_image'];
                    exit(json_encode(1));
                } elseif ($result['code'] == 2) {
                    exit(json_encode(2));
                } elseif ($result['code'] == 3) {
                    exit(json_encode(3));
                } elseif ($result['code']) {
                    exit(json_encode(5));
                }
            } else {
                //token过期
                exit(json_encode(4));
            }
        }
    }

    public function register()
    {

//        session_start();
//        $token = md5(uniqid(rand(), TRUE));
//        $_SESSION['rtoken'] = $token;
//        $_SESSION['rtoken_time'] = time();
//        $data = array(
//            'token' => $token
//        );
        $this->load->view('register');
    }

    public function registerAttestation()
    {
//        $p_token = isset($_POST['token']) ? $_POST['token'] : '';
        $username = isset($_POST['username']) ? $_POST['username'] : '';
        $password = isset($_POST['password']) ? $_POST['password'] : '';
//        $rpassword = isset($_POST['rpassword']) ? $_POST['rpassword'] : '';
        $code = isset($_POST['code']) ? $_POST['code'] : '';
        $invitecode = isset($_POST['invitecode']) ? $_POST['invitecode'] : '';
        if (empty($username) || empty($password) || empty($code) || empty($invitecode)) {
            exit(json_encode(array('code' => 0, 'msg' => '信息不全!')));
        }
        session_start();
        if (!isset($_SESSION['r_code']) || $code != $_SESSION['r_code']) {
            exit(json_encode(array('code' => 1, 'msg' => '验证码错误!')));
        }
        $this->load->model('lyw_user_model');
        if ($this->lyw_user_model->hadUsername($username)) {
            exit(json_encode(array('code' => 2, 'msg' => '用户名已经存在!')));
        }
        $this->load->model('lyw_invite_code_manager_model');
        if (!$this->lyw_invite_code_manager_model->hadCode($invitecode)) {
            exit(json_encode(array('code' => 3, 'msg' => '邀请码无效!')));
        }
        $this->load->helper('email');
        if (!isset($_SESSION['r_username']) || $_SESSION['r_username'] != $username) {
            exit(json_encode(array('code' => 4, 'msg' => '验证码无效!')));
        }
        $email = '';
        $tel = '';
        if (valid_email($username)) {
            //邮箱注册
            $email = $username;
        } else {
            $tel = $username;
        }
        $this->load->model('lyw_user_model');
        $arr = $this->lyw_user_model->add($username, $password, $invitecode, 1, $email, $tel);
        if ($arr['code'] = 1) {
            echo json_encode(array('code' => 5, 'msg' => '注册成功!'));
        } else {
            echo json_encode(array('code' => 6, 'msg' => '注册失败!'));
        }
    }

    public function getCode()
    {
        $username = isset($_POST['username']) ? $_POST['username'] : '';
        $codetype = isset($_POST['codetype']) ? $_POST['codetype'] : '';
        $type = isset($_POST['type']) ? $_POST['type'] : '';
        if (empty($username) || empty($codetype)) {
            exit(json_encode(0));
        }
        //检查用户名是否存在
        $this->load->model('lyw_user_model');
        if ($type == 'register' && $this->lyw_user_model->hadUsername($username)) {
            exit(json_encode(3));
        } elseif ($type == 'cpassword' && !$this->lyw_user_model->hadUsername($username)) {
            exit(json_encode(3));
        }

        $this->load->helper('email');
        sessionOpen();
        if (valid_email($username)) {
            $code = rand(1000, 9999);
            if ($codetype == 1) {
                $_SESSION['r_code'] = $code;
                $_SESSION['r_username'] = $username;
                $subject = '译之网注册邮件';
                $message = '<span style="font-size: 16px;">感谢您注册译之网,您的验证码为:</span><span style="font-size: 20px;color: #0a8ddf">' . $code . '</span>';
            } elseif ($codetype == 2) {
                $_SESSION['cp_code'] = $code;
                $_SESSION['cp_username'] = $username;
                $subject = '译之网修改密码';
                $message = '<span style="font-size: 16px;">译之网修改密码,您的验证码为:</span><span style="font-size: 20px;color: #0a8ddf">' . $code . '</span>';
            }
            if ($this->getCodeByEmail($username, $subject, $message)) {
                exit(json_encode(1));
            } else {
                exit(json_encode(2));
            }
        } else {
//            exit(json_encode(4));
            if (preg_match("/^1[34578]\d{9}$/", $username)) {
                $code = rand(1000, 9999);
                if ($codetype == 1) {
                    $_SESSION['r_code'] = $code;
                    $_SESSION['r_username'] = $username;
                } else {
                    $_SESSION['cp_code'] = $code;
                    $_SESSION['cp_username'] = $username;
                }
//                exit(json_encode(4));
                $this->getCodeByTel($code, $username);
                exit(json_encode(1));
            } else {
                exit(json_encode(2));
            }
        }
    }

    public function getCodeByEmail($email, $subject, $message)
    {

        $this->load->library('email');
        //以下设置Email参数
        $config['protocol'] = 'smtp';
        $config['smtp_host'] = 'smtp.163.com';
        $config['smtp_user'] = 'yi_zai_wang@163.com';
        $config['smtp_pass'] = 'yizaiwang123';
        $config['smtp_port'] = '25';
        $config['charset'] = 'utf-8';
        $config['wordwrap'] = TRUE;
        $config['mailtype'] = 'html';
        $this->email->initialize($config);
        //以下设置Email内容
        $this->email->from('yi_zai_wang@163.com', '译之网');//发件人
        $this->email->to("{$email}");
        $this->email->subject($subject);
        $this->email->message($message);
//        $this->email->attach('application\controllers\1.jpeg');           //相对于index.php的路径
        return $this->email->send();
//        var_dump($this->email->print_debugger());
    }

    public function getCodeByTel($code, $tel)
    {
        $this->load->helper('url');
        define('TOP_SDK_WORK_DIR', BASEPATH . ('../assets/alidayu/'));
//        define('TOP_AUTOLOADER_PATH', BASEPATH . ('../assets/alidayu/top/'));
        require_once BASEPATH . ('../assets/alidayu/TopSdk.php');
        $c = new TopClient();
        $c->appkey = '23582553';
        $c->secretKey = '2d836ad9cb39f4d9c747768dd86b29bb';
        $req = new AlibabaAliqinFcSmsNumSendRequest;
        $req->setExtend("");
        $req->setSmsType("normal");
        $req->setSmsFreeSignName("译之网");
        $req->setSmsParam("{code:'{$code}'}");
        $req->setRecNum($tel);
        $req->setSmsTemplateCode("SMS_50970001");
        $resp = $c->execute($req);
        return true;
    }

    /**
     * 更改密码页面
     */
    public function cPassword()
    {
        $this->load->helper('url');
        $this->load->view('admin_cpassword');
    }

    /**
     * 获取验证码图片
     */
    public function getAuthCode()
    {
        $this->load->helper('captcha');
        $this->load->helper('url');
        sessionOpen();
//        session_start();
        $word = rand(1000, 9999);
        $_SESSION['cp_randword'] = $word;
        $vals = array(
            'word' => $word,
            'img_path' => './assets/captcha/',
            'img_url' => base_url('/assets/captcha/'),
//            'font_path' => './path/to/fonts/texb.ttf',
            'img_width' => '100',
            'img_height' => 34,
            'expiration' => 1200,
            'word_length' => 13,
            'font_size' => 30,
//            'img_id' => 'Imageid',
            'pool' => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
            'colors' => array(
                'background' => array(248, 248, 255),
                'border' => array(255, 255, 255),
                'text' => array(0, 0, 0),
                'grid' => array(255, 40, 40)
            )
        );

        $cap = create_captcha($vals);
        echo json_encode($cap);
    }

    /**
     * 验证验证码图片(比较放在了JS里面,这里只验证账号是否存在)
     */
    function cpAuthCodeAttestation()
    {
//        $auth_code = isset($_POST['auth_code']) ? $_POST['auth_code'] : '';
        $username = isset($_POST['username']) ? $_POST['username'] : '';
        if (empty($username)) {
            exit(json_encode(0));
        }
        session_start();
        $this->load->model('lyw_user_model');
        if ($this->lyw_user_model->hadUsername($username)) {
            exit(json_encode(1));
        } else {
            exit(json_encode(2));
        }
    }

    /**
     * 验证验证码
     */
    function cpCodeAttestation()
    {
        $username = isset($_POST['username']) ? $_POST['username'] : '';
        $code = isset($_POST['code']) ? $_POST['code'] : '';
        if (empty($username) || empty($code)) {
            exit(json_encode(0));
        }
        sessionOpen();
//        session_start();
        if (!isset($_SESSION['cp_code']) || $code != $_SESSION['cp_code']) {
            exit(json_encode(array('code' => 1, 'msg' => '验证码错误!')));
        }
        if (!isset($_SESSION['cp_username']) || $_SESSION['cp_username'] != $username) {
            exit(json_encode(array('code' => 2, 'msg' => '验证码无效!')));
        }
        $_SESSION['change_password'] = 1;
        exit(json_encode(array('code' => 3, 'msg' => 'OK!')));
    }

    /**
     * 对用户密码进行修改
     */
    public function cpasswordChange()
    {
        $password1 = isset($_POST['password1']) ? $_POST['password1'] : '';
        $password2 = isset($_POST['password2']) ? $_POST['password2'] : '';
        $this->load->model('lyw_user_model');
        sessionOpen();
        if ($this->lyw_user_model->cPassword($_SESSION['cp_username'], $password1)) {
            exit(json_encode(1));
        } else {
            exit(json_encode(2));
        }
    }

    public function logout()
    {
        session_start();
        session_unset();
        session_destroy();
        $arr = array(
            'al_username' => '',
            'al_order' => '',
            'al_token' => '',
        );
        $this->securitycenter->setCookieList($arr);
        exit(json_encode('success'));
    }

    public function userCenter()
    {
        Permission::yy();
        $data = $this->lyw_common_model->doUserCenter();
        $this->load->view('admin_user_center.php', $data);
    }


    public function readOriginalArticleByManagerId()
    {//taskworker也需要使用
//        Permission::yy();
        Permission::check();
        $article = $this->lyw_common_model->readOriginalArticleByManagerId();
        $data = array(
            'article' => $article,
            'header_json' => $this->lyw_common_model->buildHeaderJson(),
        );
        $this->load->view('admin_read', $data);
    }

    public function myTask()
    {
        Permission::yy();
        $user_id = $_SESSION['user_id'];
        $data = array(
            'user_id' => $user_id,
            'header_json' => $this->lyw_common_model->buildHeaderJson(),
        );
        $this->load->view('admin_my_task', $data);
    }

    public function translation()
    {
        Permission::yy();
        $this->load->view('admin_translation', $this->lyw_common_model->readTranslation());
    }

    public function proofread()
    {
        Permission::yy();
        $this->load->view('taskworker_proofead', $this->lyw_common_model->readProofread());
    }

    public function changeHeaderImg()
    {
        if (isset($_FILES['header_image']) && $_FILES['header_image']['size'] > 0) {
            if (strpos($_FILES['header_image']['type'], 'image') !== false) {
                //有修改头像
                $header_image = $this->lyw_common_model->changeHeaderImg($_FILES['header_image']);
                exit(json_encode('success'));
            } else {
                exit(json_encode('类型错误!'));
            }
        } else {
            exit(json_encode('内容为空!'));
        }
    }

    public function getShouZhiJson()
    {
        Permission::yy();
        $user_id = $_SESSION['user_id'];
        $this->load->model('Lyw_gaofei_record_model');
        $this->load->model('Lyw_tixian_record_model');
        $gaofei_arr = $this->Lyw_gaofei_record_model->getListByUserId($user_id);
        $tixian_arr = $this->Lyw_tixian_record_model->getListByUserId($user_id);
        $my_arr = array();
        foreach ($gaofei_arr as $k => $v) {
            $my_arr[$v['creat_time']]['type'] = 1;
            $my_arr[$v['creat_time']]['money'] = $v['money'];
            $my_arr[$v['creat_time']]['creat_time'] = date('Y-m-d H:i:s', $v['creat_time']);
        }
        foreach ($tixian_arr as $k => $v) {
            $my_arr[$v['creat_time']]['type'] = 2;
            $my_arr[$v['creat_time']]['money'] = $v['money'];
            $my_arr[$v['creat_time']]['creat_time'] = date('Y-m-d H:i:s', $v['creat_time']);
        }
        krsort($my_arr);
        $output = array_slice($my_arr, 0, 5);
        exit(json_encode($output));
    }

    public function tixian()
    {
        Permission::yy(1);
        if (date('d') > 3) {
            exit(json_encode('请在每月的1~3号进行提现,谢谢!'));
        }
        $user_id = $_SESSION['user_id'];
        $zhifubao_account = isset($_POST['zhifubao_account']) ? $_POST['zhifubao_account'] : '';
        $this->load->model('Lyw_user_model');
        $user = $this->Lyw_user_model->getUserInfor($user_id);
        if (empty($user['zhifubao_account'])) {
            $this->Lyw_user_model->updateZhiFuBao($user_id, $zhifubao_account);
        }
        $this->load->model('Lyw_tixian_record_model');
        $this->Lyw_tixian_record_model->tixian($user_id, $user['money'], $zhifubao_account);
        exit(json_encode('提现申请提交成功,请耐心等待工作人员审核付款!'));
    }

    public function getHeaderUserJson()
    {
        Permission::yy(1);
        $this->load->model('Lyw_user_model');
        $user = $this->Lyw_user_model->getUserInfor($_SESSION['user_id']);
        $level_arr = calculateLevel($user['jingyan']);
        //获取倒计时
        $this->load->model('Lyw_article_manager_model');
        $base_new_article_manager = $this->Lyw_article_manager_model->unfinishedByUserId($_SESSION['user_id'], $_SESSION['user_type']);
        exit(json_encode(array(
            'user' => $user,
            'level_arr' => $level_arr,
            'base_new_article_manager' => empty($base_new_article_manager) ? array() : $base_new_article_manager[0],
            'can_time' => (empty($base_new_article_manager) || $base_new_article_manager[0]['translationed_time'] == 0) ? 0 : ($base_new_article_manager[0]['translationed_time'] - time())
        )));
    }

    public function translationOverDueCheck()
    {
        $this->lyw_common_model->translationOverDueCheck();
        exit(json_encode('success'));
    }
}